import React, { useEffect, useState } from 'react'
import {
    View, Swiper, SwiperItem, Image
} from '@tarojs/components'
import { getBannerList, getNavList, getProList } from '../../api/home'
import './home.scss'
import { AtGrid, AtIcon } from "taro-ui"

import ProList from '../../components/ProList'

import Taro, { useReachBottom, usePageScroll, usePullDownRefresh } from '@tarojs/taro'

export default function Home() {

    const [banner, setBanner] = useState([])
    const [navList] = useState(getNavList())
    const [pro, setPro] = useState([])

    const [count, setCount] = useState(2)

    const [scrollTop, setScrollTop] = useState(0)

    useEffect(() => {
        getBannerList().then(res => {
            // console.log(res.data);
            setBanner(res.data)
        })
        getProList().then(res => {
            setPro(res.data)
        })
    }, [])

    // 监听用户上拉触底事件。等同于 onReachBottom 页面生命周期钩子。
    useReachBottom(() => {
        getProList({ count }).then(res => {
            if (res.data.length <= 0) {
                // 没有更多了
                Taro.showToast({
                    title: '没有更多数据了.'
                })
            } else {
                setPro([...pro, ...res.data])
                setCount(count + 1)
            }

        })
    })

    usePageScroll(({ scrollTop }) => {
        // console.log(scrollTop)
        setScrollTop(scrollTop)
    })


    usePullDownRefresh(() => {
        // console.log('onPullDownRefresh')
        getProList().then(res => {
            setPro(res.data)
            setCount(2)
            // 关闭当前页面的下拉刷新
            Taro.stopPullDownRefresh()
        })
    })



    return (
        <View>

            <Swiper
                className='test-h'
                indicatorColor='#999'
                indicatorActiveColor='#F66'
                circular
                indicatorDots
                autoplay>
                {banner.map(item => {
                    return (<SwiperItem key={item.bannerid}>
                        <Image src={item.img} />
                    </SwiperItem>)
                })}

            </Swiper>

            <AtGrid className='grid' columnNum={5} hasBorder={false} data={navList} />


            <ProList prolist={pro} />
            {/* <AtList>
                {pro.map(item => {
                    return (<AtListItem
                        key={item.proid}
                        title={item.proname}
                        thumb={item.img1}
                    />)
                })}
            </AtList> */}


            {scrollTop >= 300 && <AtIcon onClick={() => {
                Taro.pageScrollTo({
                    scrollTop: 0,
                })
            }} className='back-top' value='chevron-up' size='30' ></AtIcon>}

        </View>
    )
}
